import Router from 'koa-router'
import * as postService from '../services/post.js'
export const router = new Router()

// 发布表单页
router.get('/publish', async function (ctx) {
  await ctx.render('publish')
})

// 发布处理
router.post('/publish', async function (ctx) {
  const data = ctx.request.body
  if (!data.title || !data.content) {
    ctx.throw(400, '您的请求有误')
  }
  const item = await postService.publish(data.title, data.content)
  ctx.redirect(`/post/${item.id}`)
})

// 详情页
router.get('/post/:postId', async function (ctx) {
  const post = await postService.show(ctx.params.postId)
  if (!post) {
    ctx.throw(404, '文章不存在')
  }
  await ctx.render('post', { post })
})

// 编辑表单页
router.get('/update/:postId', async function (ctx) {
  const post = await postService.show(ctx.params.postId)
  if (!post) {
    ctx.throw(404, '文章不存在')
  }
  await ctx.render('update', { post })
})

// 编辑处理
router.post('/update/:postId', async function (ctx) {
  const data = ctx.request.body
  if (!data.title || !data.content) {
    ctx.throw(400, '您的请求有误')
  }
  const postId = ctx.params.postId
  await postService.update(postId, data.title, data.content)
  ctx.redirect(`/post/${postId}`)
})

// 删除
router.get('/delete/:postId', async function (ctx) {
  await postService.deleteOne(ctx.params.postId)
  ctx.redirect('/')
})

// /api/api/v1/auth/captcha
